package com.fagp.mew.cms.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class IpUtils {

    //根路径
    public static String rootpath = System.getProperty("user.dir");

    private IpUtils() {
    }

    /**
     * 获取当前网络ip
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /**
     * 获得MAC地址
     *
     * @param ip
     * @return
     */
    public static String getMACAddress(String ip) throws Exception {

        String line = "";
        String macAddress = "";
        final String MAC_ADDRESS_PREFIX = "MAC 地址 = ";
        final String LOOPBACK_ADDRESS = "127.0.0.1";
        //如果为127.0.0.1,则获取本地MAC地址。
        if (LOOPBACK_ADDRESS.equals(ip)) {
            InetAddress inetAddress = InetAddress.getLocalHost();
            //貌似此方法需要JDK1.6。
            byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
            //下面代码是把mac地址拼装成String
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                if (i != 0) {
                    sb.append("-");
                }
                //mac[i] & 0xFF 是为了把byte转化为正整数
                String s = Integer.toHexString(mac[i] & 0xFF);
                sb.append(s.length() == 1 ? 0 + s : s);
            }
            //把字符串所有小写字母改为大写成为正规的mac地址并返回
            macAddress = sb.toString().trim().toUpperCase();
            return macAddress;
        }
        //获取非本地IP的MAC地址
        try {
            Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);

            InputStreamReader isr = new InputStreamReader(p.getInputStream(), "gbk");
            BufferedReader br = new BufferedReader(isr);
            while ((line = br.readLine()) != null) {
                if (line != null) {
                    int index = line.indexOf(MAC_ADDRESS_PREFIX);
                    if (index != -1) {
                        macAddress = line.substring(index + MAC_ADDRESS_PREFIX.length()).trim().toUpperCase();
                    }
                }
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return macAddress;
    }

    public static boolean verifyIp(HttpServletRequest request) {
        String userip = getIpAddr(request);

        return verifyIp(userip);
    }

    public static boolean verifyIp(String userip) {

        System.out.println(userip);
        String url = rootpath + "/excel/ip.txt";
        //没配置 true
        if (!new File(url).exists()){
            return true;
        }
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(url));
            int n = 0;
            StringBuilder builder = new StringBuilder();
            while ((n = in.read())!=-1){
                builder.append((char)n);
            }
            String txt = builder.toString();
            if (StringUtils.isEmpty(txt)){
                in.close();
                return true;
            }

            txt = txt.replaceAll("\\s*","");
            String[] split = txt.split(",");
            if (Arrays.stream(split).filter(i->i.equals(userip)).count()>0){
                in.close();
                return true;
            }

            List<String> collect = Arrays.stream(split).filter(i -> i.indexOf("-") > -1).collect(Collectors.toList());

            if (!collect.isEmpty()){
                //192.168.0.123-192.168.0.125
                String[] uip = userip.split("\\.");
                for (String s : collect) {
                    String[] ips = s.split("-");
                    String[] ips0 = ips[0].split("\\.");
                    String[] ips1 = ips[1].split("\\.");

                    if (uip.length!=ips0.length){
                        continue;
                    }

                    int eq = 0;

                    for (int i = 0; i < uip.length; i++) {
                        int uipp = Integer.parseInt(uip[i]);
                        if (uipp >= Integer.parseInt(ips0[i]) && uipp <= Integer.parseInt(ips1[i])){
                            eq++;
                        }
                    }

                    if (eq==uip.length){
                        in.close();
                        return true;
                    }

                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null!=in){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return false;

    }

    public static boolean verifyIpYm(HttpServletRequest request) {
        String userip = getIpAddr(request);

        return verifyIpYm(userip);
    }

    public static boolean verifyIpYm(String userip) {

        System.out.println(userip);
        String url = rootpath + "/excel/ym.txt";
        //没配置 true
        if (!new File(url).exists()){
            return false;
        }
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(url));
            int n = 0;
            StringBuilder builder = new StringBuilder();
            while ((n = in.read())!=-1){
                builder.append((char)n);
            }
            String txt = builder.toString();
            if (StringUtils.isEmpty(txt)){
                in.close();
                return false;
            }

            txt = txt.replaceAll("\\s*","");
            String[] split = txt.split(",");
            if (Arrays.stream(split).filter(i->i.equals(userip)).count()>0){
                in.close();
                return true;
            }

            List<String> collect = Arrays.stream(split).filter(i -> i.indexOf("-") > -1).collect(Collectors.toList());

            if (!collect.isEmpty()){
                //192.168.0.123-192.168.0.125
                String[] uip = userip.split("\\.");
                for (String s : collect) {
                    String[] ips = s.split("-");
                    String[] ips0 = ips[0].split("\\.");
                    String[] ips1 = ips[1].split("\\.");

                    if (uip.length!=ips0.length){
                        continue;
                    }

                    int eq = 0;

                    for (int i = 0; i < uip.length; i++) {
                        int uipp = Integer.parseInt(uip[i]);
                        if (uipp >= Integer.parseInt(ips0[i]) && uipp <= Integer.parseInt(ips1[i])){
                            eq++;
                        }
                    }

                    if (eq==uip.length){
                        in.close();
                        return true;
                    }

                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null!=in){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return false;

    }


}